<?php


namespace app\index\common;


use think\Controller;
use Firebase\JWT\JWT;

class Auth extends Controller
{

    public function _initialize()
    {
        parent::_initialize();

        if (request()->action() !== 'login' && request()->method() === 'POST') {

            $header = request()->header();
            if (isset($header['authorization']) && !empty($header['authorization'])) {
                $jwt = substr($header['authorization'], 7);
                $key   = config('jwt', NULL);
                $data = JWT::decode($jwt, $key, array('HS256'));

                if (time() > $data->exp) {
                    exit(Rsa::publicEncrypt(json_encode([
                        'code' => 500,
                        'msg' => 'jwt已过期！',
                        'data' => []
                    ])));
                }

                if (time() - $data->exp < 3600) {
                    $key   = config('jwt', NULL);
                    $time  = time();
                    $token = array(
                        "iss" => "http://rosae.vip",
                        "aud" => "rosae",
                        "iat" => $time,
                        "exp" => $time + 86400,
                        "data" => $data
                    );
                    $jwt = JWT::encode($token, $key);

                }


            }

        }
    }

}